<?php
  # Debug helper
  define("DEBUG_MODE",false);
  
  include('data/lib_f_pictures.inc.php');
  include('data/lib_f_validate.inc.php');
  include('data/lib_f_zip.inc.php');
  include('data/lib_components.inc.php');
  # Override the defaults in f_pictures.inc.php
  include('data/v_global.inc.php');
  $content ='';

  /**
  * Check what the member may do with the galleries
  * Only Comittee members or webmasters can create/add galleries.
  */
  $edit = $_SESSION['logged'] && ($_SESSION['rights'] & ($r_comittee | $r_webmaster));
  
  /**
  * Create a new gallery
  */
  if ($_POST['creategallery']) {
      extract($_POST);
      # Set up folder for gallery
      if (!$Folder = validateFilename($Name)) $Folder = date("Ymd").'_1';
      $Folder .= '/';
      while (is_dir(GALERIEDIR.$Folder)) {
          $Folder = date("Ymd").'_'.++$tmp_x.'/';
      }
      include_once('data/lib_f_dir.inc.php');
      forceDir(GALERIEDIR.$Folder);
      # create gallery
      $GID = mq("INSERT INTO galleries (MID,Name,Folder,Date) VALUES (".$_SESSION['MID'].",'$Name','$Folder','$Date')");
      logevent("Gallery created: \'$Name\' ($GID)");
  }
  
  /**
  * Process added pictures
  */
  if ($_POST['pics_submitted']) {
         extract(mqs("SELECT GID,Folder FROM galleries WHERE GID=".$_POST['GID']));
         if (DEBUG_MODE) echo 'pics submitted.<br>';
       # single pics
         for ($x=1;$x<$picuploadforms+1;$x++) {
             if (DEBUG_MODE) echo 'processing pic '.$x.'.<br>';
             if ($_FILES['Pic'.$x]['name'] = validateFilename($_FILES['Pic'.$x]['name'])) {
                 if (uploadPicture($_FILES['Pic'.$x],GALERIEDIR.$Folder,$validpictypes,$maximgheight,$maximgwidth,$maximgsize,$picmsg)) {
                   if (DEBUG_MODE) echo 'pic '.$x.' successfully been uploaded.<br>';  
                   $URL = $_FILES['Pic'.$x]['name'];
                   createThumb(GALERIEDIR.$Folder.$URL,$thumbwidth,$thumbheight);
                  # Validate names
                   if (!$_POST['Name_Pic'.$x]) $_POST['Name_Pic'.$x] = substr($_FILES['Pic'.$x]['name'],0,strlen($_FILES['Pic'.$x]['name'])-4);
                  # Insert into database
                   mq("INSERT INTO galleries_pics (GID,Name,URL) VALUES ($GID,'".$_POST['Name_Pic'.$x]."','".$URL."')");
                 } else { $err .= $picmsg;  $_FILES['Pic'.$x]['name'] = null; };
             }
             if (DEBUG_MODE) echo 'error: '.$err.'.<br>';
         }
         
         
       # ZIP part (currently the server's zip functions are disabled. currently = 30.09.07)  
         if (DEBUG_MODE) echo 'ZIP_SUPPORT:'.ZIP_SUPPORT.' - ZIP_error: '.$_FILES['ZIP']['error'].'<br>';
         if (ZIP_SUPPORT && $_FILES['ZIP']['error'] == 0) {
            if (DEBUG_MODE) echo 'zip okay<br>';
            
            $_FILES['ZIP']['name'] = validateFilename($_FILES['ZIP']['name']);
            
            # function to create thumb & database entry for file
             function handleNewPic($filename) {
                global $GID,$Folder,$thumbheight,$thumbwidth;
                mq("INSERT INTO galleries_pics (GID,Name,URL) VALUES ($GID,'".$filename."','".$filename."')");
                createThumb(GALERIEDIR.$Folder.$filename,$thumbwidth,$thumbheight);
             }
             if (DEBUG_MODE) {
                echo 'Move file from '.$_FILES['ZIP']['tmp_name'].' to '.GALERIEDIR.$Folder.$_FILES['ZIP']['name'].'<br>';
                echo move_uploaded_file($_FILES['ZIP']['tmp_name'],GALERIEDIR.$Folder.$_FILES['ZIP']['name']).'<br>';
             }  else move_uploaded_file($_FILES['ZIP']['tmp_name'],GALERIEDIR.$Folder.$_FILES['ZIP']['name']);
             $fold = GALERIEDIR.$Folder; #$_SERVER['DOCUMENT_ROOT'].'/'.
             $file = $fold.$_FILES['ZIP']['name'];
             if (DEBUG_MODE) echo 'Unzip-Folder: '.$file.'<br>';
             if (($zip = unzip_to_folder($file,$fold,true,'handleNewPic')) !== true) $err .= $zip;
             if (DEBUG_MODE) echo $zip.'<br>';
         }
         mq("UPDATE galleries SET Pics=".mqs("SELECT COUNT(BID) FROM galleries_pics WHERE GID=".$GID)." WHERE GID=".$GID);
  }
  
  if ($_GET['GID']) {
    $GID = $_GET['GID'];
  }
  
  /**
  * Delete a picture
  */
  if ($_GET['deletepic'] && $edit) {
     if ($d = mqs("SELECT g.Folder,gb.URL,gb.BID,g.GID FROM galleries_pics gb INNER JOIN galleries g ON g.GID=gb.GID WHERE gb.BID=".$_GET['deletepic'])) {
         mq("DELETE FROM galleries_pics WHERE BID=".$d[2]);
         deletePic(GALERIEDIR.$d[0].$d[1]);
         mq("UPDATE galleries SET Pics='".mqs("SELECT COUNT(BID) FROM galleries_pics WHERE GID=".$d[3])."' WHERE GID=".$d[3]);
     }
  } else if ($_GET['deletegallery']) {
     if ($data = mqs("SELECT GID,Folder FROM galleries WHERE GID=".$_GET['deletegallery'])) {
       include('data/lib_f_dir.inc.php');
       mq("DELETE FROM galleries WHERE GID=".$data[0]);
       mq("DELETE FROM galleries_pics WHERE GID=".$data[0]);
       eraseDir(GALERIEDIR.$data[1]);
     }
  }
  
  /**
   * Display a gallery
   */
  if ($GID) {
      if ($galdata = mqs("SELECT Name,Date,GID,Folder,MID FROM galleries WHERE GID=".$GID)) {
          extract($galdata);
          if ($err) $content .= $err;
          $content .= '<a href="'.$_SERVER['PHP_SELF'].'" title="Back to overview">Back to overview</a><br>';
          $content .= 'Pics in <b>'.$Name.'</b> - '.formatDate($Date).'<br>';
          if ($res = mq("SELECT BID,Name,URL FROM galleries_pics WHERE GID=".$GID." ORDER BY BID ASC")) {
              $content .= '<script type="text/javascript">
                    function showpic(nr) {
                     if (nr) {
                       pic = window.open("showpic.php?nr="+nr,"Bildansicht","location=no,scrollbars=no,menu=no,dependent=yes,status=no");
                       pic.focus();
                     }
                    }
                    </script>
                    <table width="100%" cellpadding="3" cellspacing="0"><tr>';
              while($d = mysql_fetch_row($res)) {
                $content .= '<td style="text-align:left; vertical-align:top">
                               <a href="javascript:showpic('.$d[0].')">'.getPic(getThumb(GALERIEDIR.$Folder.$d[2]),$thumbwidth,$thumbheight,$d[1]).'</a>
                               '.($edit && ($_SESSION['rights'] & $r_webmaster || $_SESSION['MID'] == $MID) 
                                  ? '<a href="'.$_SERVER['PHP_SELF'].'?GID='.$GID.'&deletepic='.$d[0].'" onclick="return confirm(\'Delete Picture? This cannot be undone.\')">
                                       <img src="'.BILDERDIR.'del.gif" alt="del">
                                     </a>'
                                  :'').'
                               '.(true ? '':$d[1]).'
                             </td>';
                if (++$x % $imagecols == 0) $content .= '</tr><tr>'; 
              }
              $content .= '</tr></table>';
          }
          if (!$edit) mq("UPDATE galleries SET Hits=Hits+1 WHERE GID=$GID");
          
          /**
          * Add new pictures
          */
          if ($edit && ($_SESSION['rights'] & $r_webmaster || $_SESSION['MID'] == $MID)) {
            $content .= '<form action="'.$_SERVER['PHP_SELF'].'" method="POST" enctype="multipart/form-data">
                         <br>
                         The names are optional.<br>
                         <table class="text" cellspacing="5" border="0">'; 
            for ($x = 1; $x < $picuploadforms+1; $x++) {
                 $content.= '<tr>
                <td><b>Add picture '.$x.':</b></td>
               </tr><tr>
                <td>Name <input type="text" name="Name_Pic'.$x.'" size="23" class="textfeld">
                </td>
               </tr>
               <tr>
                <td><input type="file" name="Pic'.$x.'" size="30" class="textfeld"></td>
               </tr>';
               }
            $content .= '</table><br>';   
            
            if (ZIP_SUPPORT) $content .= '<br>
                         Add some pictures by selecting a zip file that contains the pictures (in the root folder of the zipfile!):<br>
                         <input type="file" name="ZIP" size="50" class="text"><br>
                         <br>';
            $content .= '<input type="hidden" name="GID" value="'.$GID.'">
                         <input type="hidden" name="pics_submitted" value="1">
                         <input type="submit" value="add pictures" class="button">
                         </form>';
          }
      }
  
  /**
   * Display gallery overview
   */
  } else { 
     if ($res = mq("SELECT GID,g.Name,Date,Pics,Hits,g.MID,m.Name AS Member FROM galleries g
                    INNER JOIN members m ON m.MID=g.MID ORDER BY Date DESC")) {
        $content = '<table style="padding:3px; width:100%" cellspacing="0">
                    <tr>'.($edit ? '<th>Del</th>':'').'<th>Date</th><th>Name</th><th>Pictures</th><th>Hits</th></tr>';
        while($d = mysql_fetch_array($res)) {
           extract($d);
           $content .= '
                 <tr>
                  '.($edit ? '<td style="text-align:center">'.($_SESSION['rights'] & $r_webmaster || $_SESSION['MID'] == $MID ? '<a href="'.$_SERVER['PHP_SELF'].'?deletegallery='.$GID.'" onclick="return confirm(\'REALLY delete gallery '.$Name.'? This cannot be undone.\')"><img src="'.BILDERDIR.'del.gif" alt="del"></a>':'').'</td>':'').'
                  <td style="text-align:center">'.formatDate($Date).'</td>
                  <td style="text-align:left"><a href="'.$_SERVER['PHP_SELF'].'?GID='.$GID.'" title="Created by '.$Member.'">'.$Name.'</a></td>
                  <td style="text-align:center">'.$Pics.'</td>
                  <td style="text-align:center">'.$Hits.'</td>
                 </tr>';
        }
        $content .= '</table>';
     } else $content = 'No galleries available yet.<br>'; 
     
     /**
     * Add a gallery
     */
     if ($edit) 
     {
         $Date = date("Y-n-d");
         $content .= '<br>
                    <form action="'.$_SERVER['PHP_SELF'].'" method="POST">
                    Add a new gallery here:<br>
                    <table cellpadding="3" cellspacing="0">
                        <tr><td>Name:</td><td><input type="text" class="text" name="Name" size="32"></td></tr>
                        <tr><td>Date:</td><td>'.datePicker('Date',$Date).'</td></tr>
                        <tr><td>done?</td><td><input type="submit" class="button" value="create"></td></tr>
                    </table>
                    <input type="hidden" name="creategallery" value="1">
                    </form>';
     }
  }
?>